package com.android.tiango.baba.act;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.UserModel;
import com.android.tiango.baba.entity.UserTagEntity;
import com.android.tiango.baba.entity.UserTagModel;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.view.AppTitleBar;

/**
 * 热词
 * 
 * @author txg
 * 
 */
public class ActHotWord extends BaBaseActivity {
	// 定义TextView的Padding属性
	private static final int PADING_TOP_BOTTOM = 15;
	private static final int PADING_LEFT_RIGHT = 25;
	// 定义TextView的Margin属性
	private static final int MARGIN_LEFT_RIGHT = 20;
	private static final int MARGIN_TOP_BOTTOM = 30;
	private static int[] mHotBackgound;
	private LinearLayout mTab_content_linearLayout;
	private SharedPreferences mPreferences;
	// private List<Integer> mTemp_clikcolor;
	private UserModel mModel; 
	private int length = 8;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_hotword);
		init();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setBack();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void init() {
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		if (null != mTitleBar) {
			mTitleBar.setTitle("点亮标签");
			mTitleBar.setImageNotBackGround();
			mTitleBar.setBackIcon(R.drawable.icon_back);
			setBackOnClickListener();
			mTitleBar.setBackOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					setBack();
				}
			});
		}
		mTab_content_linearLayout = (LinearLayout) findViewById(R.id.tab_content_linearLayout);
		mPreferences = getSharedPreferences(Constants.ShARED_NAME,
				Context.MODE_PRIVATE);
		ArrayList<UserTagModel> obj = getData();
		if (obj != null && obj.size() > 0) {
			mHotBackgound = new int[obj.size()];
			for (int i = 0; i < obj.size(); i++) {
				mHotBackgound[i] = R.drawable.keyword_bg_1;
			}
			initColor();
			initSearchKeywordsView(obj);
		} else {
			if (mModel != null) {
				doUserTag(true);
			}
		}

	}

	private void setBack() {
		Intent data = new Intent(); 
		Bundle bundle = new Bundle();
		bundle.putSerializable("usermodel", mModel);
		data.putExtras(bundle);
		setResult(200, data);
		finish();
	}

	private void initColor() {
		// mTemp_clikcolor = new ArrayList<Integer>();
		// mTemp_clikcolor.add(R.color.color_tag1);
		// mTemp_clikcolor.add(R.color.color_tag2);
		// mTemp_clikcolor.add(R.color.color_tag3);
		// mTemp_clikcolor.add(R.color.color_tag4);
		// mTemp_clikcolor.add(R.color.color_tag5);
		// mTemp_clikcolor.add(R.color.color_tag6);
		// mTemp_clikcolor.add(R.color.color_tag7);
		// mTemp_clikcolor.add(R.color.color_tag8);
	}

	private ArrayList<UserTagModel> getData() {
		ArrayList<UserTagModel> list = null;
		mModel = ShareCookie.getUserInfo();
		if (mModel != null && mModel.getUserTags() != null) {
			list = mModel.getUserTags();
		}
		return list;
	}

	private void doUserTag(final boolean isVal) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", mModel.getToken());
		httpParams.put("version", "1.0");
		client.get(HttpUrl.getUrl(HttpUrl.USERTAGS), httpParams,
				new HttpCallBack() {
					public void onHttpFailure(Exception arg0, String arg1) {
						dismissWaitingDialog();
						if (!StringUtils.isEmpty(arg1)) {
							Toast.makeText(ActHotWord.this, arg1,
									Toast.LENGTH_LONG).show();
						}
					}

					@Override
					public void onHttpStarted() {
						showWaitingDialog();
					}

					@Override
					public void onHttpSuccess(Object arg0) {
						dismissWaitingDialog();
						UserTagEntity entity = (UserTagEntity) arg0;
						ArrayList<UserTagModel> data = entity.getData();
						if (data != null && data.size() > 0) {
							mModel.setUserTags(data);
							// 重新储存
							ShareCookie.saveUserInfo(mModel);
							if (isVal) {
								mHotBackgound = new int[data.size()];
								for (int i = 0; i < data.size(); i++) {
									mHotBackgound[i] = R.drawable.keyword_bg_1;
								}
								initColor();
								initSearchKeywordsView(data);
							}
						}
					}
				}, UserTagEntity.class);
	}

	private void initSearchKeywordsView(ArrayList<UserTagModel> keywords) {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		// the display screen width
		int displayWidth = getWindowManager().getDefaultDisplay().getWidth();

		float rowWidth = 0f;
		LinearLayout rowLayout = null;
		for (int i = 0, length = keywords.size(); i < length; i++) {
			UserTagModel tag = keywords.get(i);
			String text = tag.getTagName();
			TextView keywordView = createTextView(i, tag);

			float textWidth = keywordView.getPaint().measureText(text)
					+ PADING_LEFT_RIGHT * 3 + MARGIN_LEFT_RIGHT * 3;
			rowWidth += textWidth;
			if (rowLayout == null || rowWidth > displayWidth) {
				// 创建一个新的横向布局 或者 子View超过屏幕宽度，折行显示
				rowWidth = textWidth;
				rowLayout = getHorizontalLinearLayout(lp);
				mTab_content_linearLayout.addView(rowLayout);
			}
			rowLayout.addView(keywordView);
		}
	}

	/*
	 * 生成新的水平方向的LinearLayout
	 */
	private LinearLayout getHorizontalLinearLayout(LayoutParams lp) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		layout.setLayoutParams(lp);
		layout.setGravity(Gravity.CENTER);
		return layout;
	}

	/*
	 * 创建一新的热词View
	 */
	private TextView createTextView(int position, UserTagModel tag) {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.leftMargin = MARGIN_LEFT_RIGHT;
		lp.rightMargin = MARGIN_LEFT_RIGHT;
		lp.topMargin = MARGIN_TOP_BOTTOM;
		lp.bottomMargin = MARGIN_TOP_BOTTOM;
		String text = tag.getTagName();
		int isActivated = tag.getIsActivated();

		TextView view = new TextView(getApplicationContext());
		view.setText(text);
		view.setLayoutParams(lp);
		view.setGravity(Gravity.CENTER_VERTICAL);
		view.setBackgroundResource(mHotBackgound[position]);
		view.setPadding(PADING_LEFT_RIGHT, PADING_TOP_BOTTOM,
				PADING_LEFT_RIGHT, PADING_TOP_BOTTOM);
		view.setTextAppearance(getApplicationContext(), R.style.hot_font);
		view.setFocusableInTouchMode(false);
		view.setGravity(Gravity.CENTER);
		// if(color != -1 ){
		// //证明此text存在对应的color
		// view.setBackgroundColor(getResources().getColor(color));
		// System.out.println("=====:"+mTemp_clikcolor.remove((Object)color));
		// }else{
		// 已激活
		if (isActivated == 1) {
			String color = tag.getTagColor();
			if (!StringUtils.isEmpty(color)) {
				view.setBackgroundColor(android.graphics.Color.parseColor(color));
			}
		}
		// }
		view.setOnClickListener(new MyClik(tag));
		return view;
	}

	class MyClik implements OnClickListener {
		private UserTagModel tag;

		public MyClik(UserTagModel tag) {
			this.tag = tag;
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public void onClick(View v) {
			String key = ((TextView) v).getText().toString();
			if (!StringUtils.isEmpty(isClean(tag.getTagId()))) {
				System.out.println("点击了消除：" + key + ":" + tag.getTagName());
				v.setBackgroundResource(R.drawable.keyword_bg_1);
				Editor editor = mPreferences.edit();
				editor.putString(tag.getTagId(), "");
				editor.commit();
//				mTagsArray = mTagsArray.replace(tag.getTagId() + ",", "");
				tag.setIsActivated(0);
				length++;
				return;
			}

			if (length > 0) {
				String tagID = tag.getTagId();
//				mTagsArray += tagID + ",";
				tag.setIsActivated(1);
				String color = tag.getTagColor();
				v.setBackgroundColor(android.graphics.Color.parseColor(color));
				// 每点击一次，进行设置
				Editor editor = mPreferences.edit();
				editor.putString(tagID, color);
				editor.commit();
				length--;
			} else {
				Toast.makeText(ActHotWord.this, "不可在多选择了~~~",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public String isClean(String key) {
		return mPreferences.getString(key, "");
	}
}
